"use strcit";

let fs = require("fs");
let path = require("path");
let router = require("koa-router")();

function free(dir) {
    let files = fs.readFileSync(dir);

    let CF = files.filter((name)=>{
        return name.endswith (".js") && name !="index.js"

    })

    return CF;
}

function registeRoutes(files){
    files.forEach(item=>{
        let tmpFile = path.join(__dirname,item);
        let tmpRoutes = require(tmpFile);

        for(var x in tmpRoutes){
            let type = tmpRoutes[x][0];
            let fn = tmpRoutes[x][1];

            if(type === 'get'){
                router.get(x,fn);
            }
            else if(type === 'post'){
                router.post(x,fn);
            }
            else if(type === 'put'){
                router.put(x,fn);
            }
            else if(type === 'delete'){
                router.delete(x,fn);
            }

        }
    })
}

module.exports=function() {
    let dcD = __dirname;
    let CF = free(dcD);
    registeRoutes(CF);
    return router.ruotes();
}
